﻿using CPPEI.Coolzon.Common;
using CPPEI.Coolzon.Event.Core;
using CPPEI.Coolzon.Event.NCL;
using CPPEI.Coolzon.Metadata;
using CPPEI.Coolzon.UI;
using CPPEI.Coolzon.UI.Data;
using CPPEI.Coolzon.UI.Event;
using CPPEI.Coolzon.UI.Views;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace Coolvis.Console.Theme.MainViewControl
{
    /// <summary>
    /// SelectSceneView.xaml 的交互逻辑
    /// </summary>
    public partial class SelectSceneView : UserControl, IPopup
    {
        /// <summary>
        /// 左右滚动速度，值越小滚动越快
        /// </summary>
        private int _MoveSpeed = 200;
        /// <summary>
        /// 一次滚动的偏移量
        /// </summary>
        private int _MoveOffset = 150;

        private string _ShowingParentName;
        private string _ShowingSceneName;
        private string _CheckedSceneName;
        private bool _isLoading = false;

        public SelectSceneView()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 清楚所有的按钮
        /// </summary>
        public void Clear()
        {
            foreach (var item in this.ctlMainSceneContainer.Children)
            {
                (item as ToggleButton).DataContext = null;
            }
            this.ctlMainSceneContainer.Children.Clear();
            foreach (var item in SubScenePanel.Children)
            {
                (item as ToggleButton).DataContext = null;
            }
            SubScenePanel.Children.Clear();

            if (this.Parent != null)
            {
                (this.Parent as Panel).Children.Remove(this);
            }
            Logger.InfoToTag(Library.LogTAG, "SelectSceneView.Clear");
        }

        public void SetCurrentScene(string sceneName)
        {
            RenderView renderView = (RenderView)UIContext.Current.RenderView;
            if (string.IsNullOrEmpty(sceneName))
            {
                sceneName = renderView.CurrentScene.Name;
            }
            Scene parentScene = SolutionUtil.GetParentScene(UIContext.Current.Solution, sceneName);

            if (parentScene != null)
            {
                _ShowingParentName = parentScene.Name;
                SetShowingScene(parentScene.Name, this.ctlMainSceneContainer);
                BindScene(SubScenePanel, parentScene, 120, 120, true);
                SetShowingSubScene(sceneName, SubScenePanel);
                SubGrid.Visibility = Visibility.Visible;
            }
            else if (renderView.CurrentScene.Scenes != null && renderView.CurrentScene.Scenes.Count > 0)
            {
                _ShowingParentName = sceneName;
                SetShowingScene(sceneName, this.ctlMainSceneContainer);
                BindScene(SubScenePanel, renderView.CurrentScene, 120, 120, true);
                SetShowingSubScene(sceneName, SubScenePanel);
                SubGrid.Visibility = Visibility.Visible;
            }
            else
            {
                _ShowingParentName = "";
                SetShowingScene(sceneName, this.ctlMainSceneContainer);
                Scene currentScene = SolutionUtil.GetScene(UIContext.Current.Solution, sceneName);
                if (renderView.CurrentScene.Scenes != null && renderView.CurrentScene.Scenes.Any())
                {
                    BindScene(SubScenePanel, currentScene, 120, 120, true);
                    SubGrid.Visibility = Visibility.Visible;
                    //SetChildAvailable();
                }
                else
                {
                    SubGrid.Visibility = Visibility.Collapsed;
                    SubScenePanel.Children.Clear();
                }
            }
            _isLoading = false;
        }
        private void SetChildAvailable()
        {
            foreach (UIElement element in SubScenePanel.Children)
            {
                if (element is CheckBox)
                {
                    element.IsEnabled = true;
                }
            }
        }
        private void SetCheckedScene(string sceneName, Panel parent)
        {
            _CheckedSceneName = sceneName;
            foreach (UIElement element in parent.Children)
            {
                if (element is ToggleButton)
                {
                    ToggleButton btn = element as ToggleButton;
                    btn.IsEnabled = true;
                    if (string.Equals(btn.Name, _ShowingParentName) || string.Equals(btn.Name, _ShowingSceneName))
                    {
                        continue;
                    }
                    if (btn.Name.Equals(sceneName))
                    {
                        btn.IsChecked = true;
                    }
                    else
                    {
                        btn.IsChecked = false;
                    }
                }
            }
        }
        private void SetShowingScene(string sceneName, Panel parent)
        {
            _ShowingSceneName = sceneName;
            foreach (UIElement element in parent.Children)
            {
                if (element is ToggleButton)
                {
                    ToggleButton btn = element as ToggleButton;
                    if (btn.Name.Equals(sceneName))
                    {
                        btn.IsChecked = true;
                    }
                    else
                    {
                        btn.IsChecked = false;
                    }
                    btn.IsEnabled = true;
                }
            }
        }
        private void SetShowingSubScene(string sceneName, Panel parent)
        {
            _ShowingSceneName = sceneName;
            foreach (UIElement element in parent.Children)
            {
                if (element is Button)
                {
                    Button btn = element as Button;
                    if (btn.Name.Equals(sceneName))
                    {
                        btn.Background = (ImageBrush)this.Resources["showingSub"];
                        btn.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#172A88"));
                    }
                    else
                    {
                        btn.Background = (ImageBrush)this.Resources["normal"];
                        btn.Foreground = new SolidColorBrush(Colors.White);
                    }
                    btn.IsEnabled = true;
                }
            }
        }
        private void SetLoadingScene(string sceneName)
        {
            if (_isLoading)
            {
                return;
            }
            //foreach (UIElement element in spRecord.Children)
            //{
            //    if (element is Button)
            //    {
            //        Button btn = element as Button;
            //        if (btn.Name.Equals(sceneName) && !string.Equals(btn.Name, _ShowingSceneName) && !string.Equals(btn.Name, _ShowingParentName))
            //        {
            //            btn.Background = (ImageBrush)this.Resources["loading"];
            //            btn.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#172A88"));
            //            break;
            //        }
            //    }
            //}
            //foreach (UIElement element in SubScenePanel.Children)
            //{
            //    if (element is Button)
            //    {
            //        Button btn = element as Button;
            //        if (btn.Name.Equals(sceneName))
            //        {
            //            btn.Background = (ImageBrush)this.Resources["loadingSub"];
            //            btn.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#172A88"));
            //            break;
            //        }
            //    }
            //}
            _isLoading = true;
        }

        /// <summary>
        /// 绑定场景
        /// </summary>
        [Obsolete("不使用了")]
        public void BindScene()
        {
        }
        private void BindScene(Panel panel, Scene scene, double width, double height, bool isEnable)
        {
            panel.Children.Clear();
            int i = 0;
            Button btn = new Button();
            btn.Style = (Style)this.Resources["btnLabel"];
            btn.Name = scene.Name;
            btn.Content = "主场景";
            btn.Tag = i;
            btn.Width = width;
            btn.Height = height;
            btn.Click += btn_Click;
            btn.DataContext = scene;
            btn.IsEnabled = isEnable;
            btn.Background = (ImageBrush)this.Resources["normal"];

            panel.Children.Add(btn);
            foreach (Scene subScene in scene.Scenes)
            {
                i++;
                btn = new Button();
                btn.Style = (Style)this.Resources["btnLabel"];
                btn.Name = subScene.Name;
                btn.Content = subScene.Caption;
                btn.Tag = i;
                btn.Width = width;
                btn.Height = height;
                btn.Click += btn_Click;
                btn.DataContext = subScene;
                btn.IsEnabled = isEnable;
                btn.Background = (ImageBrush)this.Resources["normal"];

                panel.Children.Add(btn);
            }
        }

        private void btn_Click(object sender, RoutedEventArgs e)
        {
            Button btn = sender as Button;
            Scene scene = btn.DataContext as Scene;

            OpenScene(scene);
        }

        void OnBtnScrollLeftClick(object sender, RoutedEventArgs e)
        {
            double offset = ctlMainSceneScroller.HorizontalOffset;
            ctlMainSceneScroller.ScrollToHorizontalOffset(offset - 270);
        }

        void OnBtnScrollRightClick(object sender, RoutedEventArgs e)
        {
            //ctlMainSceneScroller.ScrollableWidth
            double offset = ctlMainSceneScroller.HorizontalOffset;
            ctlMainSceneScroller.ScrollToHorizontalOffset(offset+270);
        }

        void OnBtnMainSceneClick(object sender, RoutedEventArgs e)
        {
            ToggleButton btn = sender as ToggleButton;
            Scene scene = btn.DataContext as Scene;

            if (string.IsNullOrEmpty(_ShowingSceneName) == false && string.Equals(_ShowingSceneName, scene.Name))
            {
                btn.IsChecked = true;
                e.Handled = true;
                return;
            }

            if (scene.Scenes == null || scene.Scenes.Count == 0)
            {
                OpenScene(scene);
                SubGrid.Visibility = System.Windows.Visibility.Collapsed;
                if (string.Equals(scene.Name, ((RenderView)UIContext.Current.RenderView).CurrentScene.Name))
                {
                    SetCheckedScene(scene.Name, ctlMainSceneContainer);
                }
            }
            else
            {
                BindScene(SubScenePanel, scene, 120, 120, true);
                SubGrid.Visibility = System.Windows.Visibility.Visible;
                SetCheckedScene(scene.Name, ctlMainSceneContainer);
                SetShowingSubScene(_ShowingSceneName, SubScenePanel);
            }
        }

        private void OpenScene(Scene scene)
        {
            SetLoadingScene(scene.Name);

            OpenSceneArgs openSceneArgs = new OpenSceneArgs();
            openSceneArgs.ParametersString.Add("sys:isresetviewstate", "true");

            NCLEventBus.PublishAsync(
                new NCLOpenSceneEvent(SwitchMode.Replace, "", scene.Name, openSceneArgs));
        }
        /// <summary>
        /// 关闭事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void _ctlBtnClose_Click(object sender, RoutedEventArgs e)
        {
            this.Visibility = System.Windows.Visibility.Hidden;
        }

        private DispatcherTimer dispatcherTime;
        private void InitDispatcherTime()
        {
            if (dispatcherTime == null)
            {
                dispatcherTime = new DispatcherTimer();
                dispatcherTime.Tick += dispatcherTime_Tick;
                dispatcherTime.IsEnabled = false;
                dispatcherTime.Interval = TimeSpan.FromMilliseconds(_MoveSpeed);
            }
        }

        void dispatcherTime_Tick(object sender, EventArgs e)
        {

        }

        private void StopDispatcherTime()
        {
            if (dispatcherTime != null && dispatcherTime.IsEnabled)
            {
                dispatcherTime.Stop();
                dispatcherTime.IsEnabled = false;
            }
        }

        private void StartDispatcherTime(int direction)
        {
            if (!dispatcherTime.IsEnabled)
            {
                dispatcherTime.Tag = direction;
                dispatcherTime.IsEnabled = true;
                dispatcherTime.Start();
            }
        }

        private DispatcherTimer subDispatcherTime;
        private void InitSubDispatcherTime()
        {
            if (subDispatcherTime == null)
            {
                subDispatcherTime = new DispatcherTimer();
                subDispatcherTime.Tick += subDispatcherTime_Tick;
                subDispatcherTime.IsEnabled = false;
                subDispatcherTime.Interval = TimeSpan.FromMilliseconds(_MoveSpeed);
            }
        }

        void subDispatcherTime_Tick(object sender, EventArgs e)
        {
            if (System.Windows.Input.Mouse.LeftButton == MouseButtonState.Pressed
                || System.Windows.Input.Mouse.RightButton == MouseButtonState.Pressed)
            {
                _subScrollViewer.ScrollToHorizontalOffset(_subScrollViewer.ContentHorizontalOffset + Convert.ToInt32(subDispatcherTime.Tag) * _MoveOffset);
            }
        }

        private void StopSubDispatcherTime()
        {
            if (subDispatcherTime != null && subDispatcherTime.IsEnabled)
            {
                subDispatcherTime.Stop();
                subDispatcherTime.IsEnabled = false;
            }
        }

        private void StartSubDispatcherTime(int direction)
        {
            if (!subDispatcherTime.IsEnabled)
            {
                subDispatcherTime.Tag = direction;
                subDispatcherTime.IsEnabled = true;
                subDispatcherTime.Start();
            }
        }
        #region 子场景左移
        private void leftSubLoop_Click(object sender, RoutedEventArgs e)
        {
            _subScrollViewer.ScrollToHorizontalOffset(_subScrollViewer.ContentHorizontalOffset - _MoveOffset);
        }

        private void leftSubLoop_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            InitSubDispatcherTime();
            StartSubDispatcherTime(-1);
        }

        private void leftSubLoop_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            StopSubDispatcherTime();
        }

        private void leftSubLoop_TouchDown(object sender, TouchEventArgs e)
        {
            InitSubDispatcherTime();
            StartSubDispatcherTime(-1);
        }

        private void leftSubLoop_TouchUp(object sender, TouchEventArgs e)
        {
            StopSubDispatcherTime();
        }
        #endregion

        #region 子场景右移
        private void rightSubLoop_Click(object sender, RoutedEventArgs e)
        {
            _subScrollViewer.ScrollToHorizontalOffset(_subScrollViewer.ContentHorizontalOffset + _MoveOffset);
        }

        private void rightSubLoop_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            InitSubDispatcherTime();
            StartSubDispatcherTime(1);
        }

        private void rightSubLoop_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            StopSubDispatcherTime();
        }

        private void rightSubLoop_TouchDown(object sender, TouchEventArgs e)
        {
            InitSubDispatcherTime();
            StartSubDispatcherTime(1);
        }

        private void rightSubLoop_TouchUp(object sender, TouchEventArgs e)
        {
            StopSubDispatcherTime();
        }
        #endregion

        #region 子场景触屏相关事件
        private void rightSubLoop_TouchEnter(object sender, TouchEventArgs e)
        {
            rightSubLoop.Opacity = 100;
        }

        private void rightSubLoop_TouchLeave(object sender, TouchEventArgs e)
        {
            rightSubLoop.Opacity = 0.2;
        }

        private void leftSubLoop_TouchEnter(object sender, TouchEventArgs e)
        {
            leftSubLoop.Opacity = 100;
        }

        private void leftSubLoop_TouchLeave(object sender, TouchEventArgs e)
        {
            leftSubLoop.Opacity = 0.2;
        }
        #endregion

        private void leftSubLoop_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
        {
            leftSubLoop.Opacity = 100;
        }

        private void rightSubLoop_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
        {
            rightSubLoop.Opacity = 100;
        }

        private void leftSubLoop_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
        {
            leftSubLoop.Opacity = 0.2;
        }

        private void rightSubLoop_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
        {
            rightSubLoop.Opacity = 0.2;
        }

        public void Active()
        {
            if (UIContext.Current.Solution.Scenes == null || !UIContext.Current.Solution.Scenes.Any())
                return;

            int index = 0;
            ctlMainSceneContainer.Children.Clear();
            RenderView renderView = (RenderView)UIContext.Current.RenderView;
            bool isChildScene = true;
            foreach (Scene scene in UIContext.Current.Solution.Scenes)
            {
                if (scene.IsShowInNavigation)
                {
                    index++;
                    ToggleButton btn = new ToggleButton();
                    btn.Style = (Style)this.Resources["BtnMainScene"];
                    btn.Name = scene.Name;
                    btn.Content = scene.Caption;
                    btn.Tag = index;
                    btn.Click += OnBtnMainSceneClick;
                    btn.DataContext = scene;

                    if (string.IsNullOrEmpty(_ShowingSceneName) == false && string.Equals(_ShowingSceneName, scene.Name))
                    {
                        btn.IsChecked = true;
                    }

                    ctlMainSceneContainer.Children.Add(btn);

                    if (renderView.CurrentScene != null && scene.Name.Equals(renderView.CurrentScene.Name))
                    {
                        //btn.Background = (ImageBrush)this.Resources["showing"];
                        //btn.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#172A88"));
                        isChildScene = false;
                    }
                }
            }
            //if (renderView.CurrentScene != null)
            //{
            //    if (isChildScene || (renderView.CurrentScene.Scenes != null && renderView.CurrentScene.Scenes.Any()))
            //    {
            //        Scene parentScene = SolutionUtil.GetParentScene(UIContext.Current.Solution, renderView.CurrentScene.Name);
            //        if (parentScene == null)
            //        {
            //            parentScene = renderView.CurrentScene;
            //        }
            //        SetShowingScene(parentScene.Name, ctlMainSceneContainer);
            //        BindScene(SubScenePanel, parentScene, 120, 120, true);
            //        SetShowingSubScene(renderView.CurrentScene.Name, SubScenePanel);
            //        SubGrid.Visibility = System.Windows.Visibility.Visible;
            //    }
            //}
        }

        public void Deactive()
        {
        }

        public void Destory()
        {
        }
    }
}
